#pragma once

#include "Socket.hpp"
#include "ThreadPool.hpp"
namespace TcpServerModule
{
    using namespace ThreadPoolModule;
    using namespace SocketModule;
    using tcp_ptr = std::shared_ptr<Socket>;
    const uint16_t gport = 8081;
    using handler_t = std::function<void(SockPtr,InetAddr)>;
    using task_t = std::function<void()>;
    class TcpServer
    {
    private:
        tcp_ptr _tsvr;
        bool _isrunning;
        handler_t _handler;
    public:
        TcpServer(uint16_t port = gport) : _tsvr(std::make_shared<TcpSocket>()), _isrunning(false)
        {
            _tsvr->BuildTckSocket(port);
            ThreadPool<task_t>::Getinstance()->Start();
        }
        void RegisterHandler(handler_t handler)
        {
            _handler = handler;
        }
        void Loop()
        {
            _isrunning = true;
            while (_isrunning)
            {
                InetAddr client;
                SockPtr ret = _tsvr->Acceptor(&client);
                //处理数据的任务统一交给上层
                //这里要值传递,因为进程池当中的执行方法的时候已经把锁释放掉了，所以其他线程接着acceptor，那么就会把原来的ret直接覆盖掉了。
                task_t t = [this,ret,client]() 
                {
                    _handler(ret,client);
                };
                // _handler(ret,client);
                ThreadPool<task_t>::Getinstance()->Equeue(t);
            }
            _isrunning = false;
        }

        ~TcpServer() {}
    };
}
